﻿
#region NameSpace
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Eb.StockManagement;
using Eb.MessageBox;
#endregion

public partial class Modules_StockManagement_LocalPurchase : System.Web.UI.UserControl
{
    #region Fields
    static double grdTotalGeneral = 0;
    StockManagement stockManagement = new StockManagement();
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
        SetInitialRow();
    }
    protected void lbRemove_Click(object sender, EventArgs e)
    {
        int subAmt = 0;
        string amount = string.Empty;
        int grdCount = 0;
        LinkButton lb = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
        // int rowID = gvRow.RowIndex + 1;
        int rowID = gvRow.RowIndex;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    amount = dt.Rows[rowID][4].ToString();
                    if (amount != "")
                        subAmt = Convert.ToInt32(amount);
                    //Remove the Selected Row data
                    dt.Rows.Remove(dt.Rows[rowID]);
                    grdCount = dt.Rows.Count - 1;
                }
            }
            //Store the current data in ViewState for future reference
            ViewState["CurrentTable"] = dt;
            //Re bind the GridView for the updated data
            gvItemDetails.DataSource = dt;
            gvItemDetails.DataBind();
            htmlHidden.Value = grdCount.ToString();
            if(grdTotalGeneral>=subAmt)
                grdTotalGeneral = grdTotalGeneral-subAmt;
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
    protected void gvItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //  FindTotalAmountWithGeneralPurchase();
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            LinkButton lb = (LinkButton)e.Row.FindControl("lbRemove");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = false;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[4].Text = "Total:";
        }
    }
    protected void txtRequiredQty_TextChanged(object sender, EventArgs e)
    {
        FindTotalAmountWithGeneralPurchase();
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        InsertLocalPurchase();

    }
    #region Methods
    /// <summary>
    /// To find 
    /// </summary>
    protected void FindTotalAmountWithGeneralPurchase()
    {
        double amt = 0;
        foreach (GridViewRow gvr in gvItemDetails.Rows)
        {
            TextBox tbQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTP");
            int totQty = Convert.ToInt16(tbQty.Text);


            tbTotal.Text = Convert.ToString(price1 * totQty);

            grdTotalGeneral = Convert.ToDouble(tbTotal.Text) + amt;
            amt = grdTotalGeneral;
            htmlHidden.Value = gvItemDetails.Rows.Count.ToString();

        }
        ((TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot")).Text = grdTotalGeneral.ToString("c").Replace("$", "Rs "); 
    }
    private void SetInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));
        dt.Columns.Add(new DataColumn("Column5", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dr["Column4"] = string.Empty;
        dr["Column5"] = string.Empty;
        dt.Rows.Add(dr);
        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        gvItemDetails.DataSource = dt;
        gvItemDetails.DataBind();
        htmlHidden.Value = "0";
    }
    private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtRequiredQty");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtUnitPrice");
                    TextBox box4 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtTP");
                    TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtSpecification");



                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    if (box1.Text.Trim() != "" && box2.Text.Trim() != "")
                    {
                        lblErrMessage.Visible = false;
                        lblErrMessage.Text = "";
                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
                        //  itemIndex = Convert.ToInt16(box1.SelectedValue);
                        rowIndex++;
                    }
                    else
                    {
                        lblErrMessage.Visible = true;
                        lblErrMessage.Text = "Please Fill all Fields";
                        return;
                    }
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                gvItemDetails.DataSource = dtCurrentTable;
                gvItemDetails.DataBind();
                htmlHidden.Value = gvItemDetails.Rows.Count.ToString();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
               // GetMaterials();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[4].FindControl("txtRequiredQty");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtUnitPrice");
                    TextBox box4 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[5].FindControl("txtTP");
                    TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtSpecification");
                    TextBox box6 = (TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot");
                    if (i < dt.Rows.Count - 1)
                    {
                        //   box1.ClearSelection();
                        //   box1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
                        box1.Text = dt.Rows[i]["Column1"].ToString();
                        box2.Text = dt.Rows[i]["Column2"].ToString();
                        box3.Text = dt.Rows[i]["Column3"].ToString();
                        box4.Text = dt.Rows[i]["Column4"].ToString();
                        box5.Text = dt.Rows[i]["Column5"].ToString();
                        box6.Text = grdTotalGeneral.ToString("c").Replace("$", "Rs:"); 
                    }


                    rowIndex++;
                }
            }
        }
    }

    protected void InsertLocalPurchase()
    {
        int purchaseID = 0;
        int userId = 0;
        bool status=false;
        if (Session["UserId"] != null)
            userId = Convert.ToInt16(Session["UserId"].ToString());
        purchaseID = stockManagement.InsertLocalPurchase(userId, txtRemarks.Text,grdTotalGeneral);
        if (purchaseID > 0)
        {
            foreach (GridViewRow gvr in gvItemDetails.Rows)
            {
                double unitPrice = 0;
                int qty = 0;
                TextBox txtProduct = (TextBox)gvr.Cells[1].FindControl("txtProduct");
                TextBox txtSpecification = (TextBox)gvr.Cells[2].FindControl("txtSpecification");
                TextBox txtUnitPrice = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
                TextBox txtRequiredQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
                if (txtUnitPrice.Text != null || txtUnitPrice.Text != "")
                {
                    unitPrice = Convert.ToDouble(txtUnitPrice.Text);
                }
                if (txtRequiredQty.Text != null || txtRequiredQty.Text != "")
                {
                    qty = Convert.ToInt32(txtRequiredQty.Text.Trim());
                }
                
                status = stockManagement.InsertLocalPurchaseItemDetails(purchaseID, txtProduct.Text, txtSpecification.Text, unitPrice, qty);
            }
            if (status)
                MessageBox.Show("Successfully Inserted");
            else
                MessageBox.Show("Failed to insert Purchase Details.");
        }
    }
    #endregion
   
    
}
